package com.fortune.controller;

import com.fortune.base.BaseAPIExcution;
import com.fortune.base.BaseController;
import com.fortune.dto.excution.COrderExcution;
import com.fortune.dto.excution.ClientUserExcution;
import com.fortune.dto.in.cOrder.COrderProductDto;
import com.fortune.dto.in.cOrder.COrderProductEditDto;
import com.fortune.dto.in.cOrder.PurchaseGiftDto;
import com.fortune.dto.in.clientOrder.*;
import com.fortune.entity.Order;
import com.fortune.enums.COrderEnum;
import com.fortune.enums.ClientUserEnum;
import com.fortune.exception.db.DeleteInnerErrorException;
import com.fortune.exception.db.InsertInnerErrorException;
import com.fortune.exception.db.UpdateInnerErrorException;
import com.fortune.service.COrderService;
import com.fortune.service.ClientUserService;
import com.fortune.util.UUIDUtil;
import com.fortune.vo.cOrder.CorderSubmit;
import com.fortune.vo.clientOrder.OrderDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Api(value = "wechat/client/order", description = "客户订单相关", tags = {"微信小程序（业务员）：订单管理"})
@RestController
@RequestMapping("wechat/client/order")
public class ClientOrderController extends BaseController{
	@Autowired
	private ClientUserService clientUserService;

	@Autowired
	private COrderService cOrderService;
	@ApiOperation(value = "订单列表", nickname = "clientOrderList", notes = "", tags={ "@安童" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@GetMapping(value = "list",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<List<Order>> clientOrderList(ListDto listDto) {
		String did = getDId();
		List<Order> clientOrderList=clientUserService.clientOrderList(listDto,did);
		if (clientOrderList==null){
			return new ClientUserExcution<List<Order>>(clientOrderList, ClientUserEnum.FIND_RESULT_AIR);
		}
		return new ClientUserExcution<List<Order>>(clientOrderList, ClientUserEnum.FIND_SUCCESS);
	}

	@ApiOperation(value = "添加订单", nickname = "clientOrderAdd", notes = "", tags={ "@安童" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@Transactional
	@PostMapping(value = "add",
			produces = { MediaType.APPLICATION_JSON_VALUE },
			consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<CorderSubmit> add(@Validated @RequestBody DOrderSubmitDto addDto) {
		String did = getDId();
		List<COrderProductDto> products = addDto.getProducts();
		String id = UUIDUtil.get32UUID();//订单id
		String no = UUIDUtil.get32UUID();//订单编号
		CorderSubmit corderSubmit = new CorderSubmit();
		corderSubmit.setId(id);
		corderSubmit.setNo(no);

		String clientId = addDto.getClientId();//客户id
		BigDecimal pTotalPrice = addDto.getpTotalPrice();//商品总钱数
		BigDecimal dTotalPrice = addDto.getdTotalPrice();//押金钱数
		int addCOrder = cOrderService.addCOrder(did, clientId, id, no, pTotalPrice, dTotalPrice);
		if(addCOrder < 1){
			throw new InsertInnerErrorException("添加失败！");
		}
		int a = 0;
		for(COrderProductDto cOrderProductDto : products){
			//int num = products.getNum();//总商品数量
			List<PurchaseGiftDto> sales = cOrderProductDto.getSales();//销售
			List<PurchaseGiftDto> gift = cOrderProductDto.getGift();//赠送
			//int backBox = products.getBackBox();//回空箱数量

			//销售
			for(int j = 0; j < sales.size(); j++){
				PurchaseGiftDto purchaseGiftDto = sales.get(j);
				String mid = purchaseGiftDto.getMid();
				String productId = purchaseGiftDto.getProductId();//商品ID
				int detailsNo = a + 1;
				a = detailsNo;
				float orderNum = purchaseGiftDto.getOrderNum();//订货数量
				BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
				String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
				float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
				BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
				BigDecimal price = purchaseGiftDto.getPrice();//商品金额
				BigDecimal as = new BigDecimal(orderNum);
				BigDecimal tprice = dprice.multiply(as);
				int addCOrderDetails = cOrderService.addCOrderDetails(did, clientId, id, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
				if(addCOrderDetails < 1){
					throw new InsertInnerErrorException("添加失败！");
				}
			}
			//赠送
			for(int x = 0; x < gift.size(); x++){
				PurchaseGiftDto purchaseGiftDto = gift.get(x);
				String mid = purchaseGiftDto.getMid();
				String productId = purchaseGiftDto.getProductId();//商品ID
				int detailsNo = a + 1;
				float orderNum = purchaseGiftDto.getOrderNum();//订货数量
				BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
				String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
				float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
				BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
				BigDecimal price = purchaseGiftDto.getPrice();//商品金额
				BigDecimal as = new BigDecimal(orderNum);
				BigDecimal tprice = dprice.multiply(as);
				int addCOrderDetailsByZS = cOrderService.addCOrderDetailsByZS(did, clientId, id, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
				if(addCOrderDetailsByZS < 0){
					throw new InsertInnerErrorException("添加失败！");
				}
			}
		}
		String returnPeriod = cOrderService.findReturnPeriod(did, clientId);
		int editClientHFTime = cOrderService.editClientHFTime(did, clientId, returnPeriod);
		if(editClientHFTime < 1){
			return new COrderExcution<CorderSubmit>(corderSubmit, COrderEnum.EDIT_ERROR);
		}
		return new COrderExcution<CorderSubmit>(corderSubmit, COrderEnum.ADD_SUCCESS);
	}
	
	@ApiOperation(value = "获取订单详情", nickname = "clientOrderDetail", notes = "", tags={ "@安童" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @GetMapping(value = "detail",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<OrderDetail> detail(@Validated @NotBlank(message="订单id不能为空") String orderId, @Validated @NotBlank(message="客户id不能为空") String clientId) {
		String dId = getDId();
		OrderDetail detail=clientUserService.clientOrderDetail(dId, clientId, orderId);
		return new ClientUserExcution(detail, ClientUserEnum.FIND_SUCCESS);
	}
	
	@ApiOperation(value = "提交订单(修改订单状态为已提交)", nickname = "clientOrderCommit", notes = "", tags={ "@安童" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
    @PutMapping(value = "commit",
        produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> commit(@Validated @NotBlank(message="订单id不能为空") String orderId, @Validated @NotBlank(message="客户id不能为空") String clientId) {
		String dId = getDId();
		int num = clientUserService.updateOrderStatus(dId, clientId, orderId);
		if(num > 0) {
			return new ClientUserExcution<Void>(null, ClientUserEnum.EDIT_SUCCESS);
		}
		return new ClientUserExcution<Void>(null, ClientUserEnum.EDIT_ERROR);
	}
	
	@ApiOperation(value = "编辑订单", nickname = "clientOrderEdit", notes = "", tags={ "@安童" })
	@ApiImplicitParams({
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@Transactional
    @PutMapping(value = "edit",
        produces = { MediaType.APPLICATION_JSON_VALUE },
        consumes = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> commit(@Validated @RequestBody CCClientOrderEditDto editDto) {

		String did = getDId();
		String clientId = editDto.getClientId();
		String orderId = editDto.getOrderId();//订单id
		BigDecimal pTotalPrice = editDto.getdTotalPrice();
		BigDecimal dTotalPrice = editDto.getdTotalPrice();
		int editOrder = cOrderService.editOrder(did, clientId, orderId, pTotalPrice, dTotalPrice);
		if(editOrder < 1){
			throw new UpdateInnerErrorException("编辑失败！");
		}
		int delOrder = cOrderService.delOrder(did, clientId, orderId);
		if(delOrder < 1){
			throw new DeleteInnerErrorException("删除失败！");
		}

		List<COrderProductEditDto> products = editDto.getProducts();
		int a = 0;
		for(COrderProductEditDto cOrderProductEditDto : products){
			//int num = products.getNum();//总商品数量
			List<PurchaseGiftDto> sales = cOrderProductEditDto.getSales();//销售
			List<PurchaseGiftDto> gift = cOrderProductEditDto.getGift();//赠送
			//int backBox = products.getBackBox();//回空箱数量

			//销售
			for(int j = 0; j < sales.size(); j++){
				PurchaseGiftDto purchaseGiftDto = sales.get(j);
				String mid = purchaseGiftDto.getMid();
				String productId = purchaseGiftDto.getProductId();//商品ID
				int detailsNo = a + 1;
				a = detailsNo;
				float orderNum = purchaseGiftDto.getOrderNum();//订货数量
				BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
				String policyId;
				if(purchaseGiftDto.getPolicyId() == "" || purchaseGiftDto.getPolicyId() == null){
					policyId = "无";
				}else{
					policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
				}
				float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
				BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
				BigDecimal price = purchaseGiftDto.getPrice();//商品金额
				BigDecimal tprice = dprice.add(price);
				int addCOrderDetails = cOrderService.addCOrderDetails(did, clientId, orderId, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
				if(addCOrderDetails < 0){
					throw new InsertInnerErrorException("添加失败！");
				}
			}
			if(gift.size() != 0){
				//赠送
				for(int x = 0; x < gift.size(); x++){
					PurchaseGiftDto purchaseGiftDto = gift.get(x);
					String mid = purchaseGiftDto.getMid();
					String productId = purchaseGiftDto.getProductId();//商品ID
					int detailsNo = a + 1;
					float orderNum = purchaseGiftDto.getOrderNum();//订货数量
					BigDecimal unitPrice = purchaseGiftDto.getUnitPrice();//单价
					String policyId = purchaseGiftDto.getPolicyId();//优惠政策ID
					float backBoxNum = purchaseGiftDto.getBackBoxNum();//回空箱数量
					BigDecimal dprice = purchaseGiftDto.getDprice();//押金金额
					BigDecimal price = purchaseGiftDto.getPrice();//商品金额
					BigDecimal tprice = dprice.add(price);
					int addCOrderDetailsByZS = cOrderService.addCOrderDetailsByZS(did, clientId, orderId, detailsNo, mid, productId, orderNum, price, policyId, unitPrice, backBoxNum, dprice, tprice);
					if(addCOrderDetailsByZS < 0){
						throw new InsertInnerErrorException("添加失败！");
					}
				}
			}
		}
		String returnPeriod = cOrderService.findReturnPeriod(did, clientId);
		int editClientHFTime = cOrderService.editClientHFTime(did, clientId, returnPeriod);
		if(editClientHFTime < 0){
			return new COrderExcution<Void>(null, COrderEnum.EDIT_ERROR);
		}
		return new COrderExcution<Void>(null, COrderEnum.EDIT_SUCCESS);
	}

	@ApiOperation(value = "删除订单", nickname = "clientOrderDelete", notes = "", tags = {"@郭阳"})
	@ApiImplicitParams({
			@ApiImplicitParam(name="orderId", value="订单id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="clientId", value="客户id",paramType="query",dataType="string"),
			@ApiImplicitParam(name="Authorization", value="登录返回的token值",paramType="header",dataType="String",required = true)
	})
	@DeleteMapping(value = "delete",
			produces = { MediaType.APPLICATION_JSON_VALUE })
	public BaseAPIExcution<Void> delete(@Validated @NotBlank(message="订单id不能为空") String orderId,@Validated @NotBlank(message="客户id不能为空") String clientId){
		String did = getDId();
		int deleteCOrder = cOrderService.deleteCOrder(did, clientId, orderId);
		if(deleteCOrder < 1){
			return new COrderExcution<Void>(null, COrderEnum.DELETE_ERROR);
		}
		return new COrderExcution<Void>(null, COrderEnum.DELETE_SUCCESS);
	}
}
